package com.zelin.model.service;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * TCP通信:
 * 服务端
 */
public class TcpServer {
    public static void main(String[] args) {
        ServerSocket server = null;
        Socket socket = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;

        //定义服务端对象,并指定接入的端口号
        try {
            server = new ServerSocket(6666);
            System.out.println("服务端已创建!");

            //等待客户端接入,接入后返回一个客户端的对象
            socket = server.accept();
            System.out.println("客户端已接入");

            //获得客户端发送的字节流,返回字节流对象
            inputStream = socket.getInputStream();
            //定义字节数组存储字节流数据
            byte[] b = new byte[1024];
            //读入数据
            int len = inputStream.read(b);
            //将数组数据转为字符串
            String s = new String(b, 0, len);
            System.out.println("客户端:" + s);

            //服务端向客户端发送数据
            outputStream = socket.getOutputStream();
            String str = "你好,客户端,好久不见";
            outputStream.write(str.getBytes());
            System.out.println("服务端数据已发送");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                assert outputStream != null;
                outputStream.flush();
                outputStream.close();
                inputStream.close();
                socket.close();
                server.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
